package com.oa.duban.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.err.BizException;
import com.mdp.core.service.BaseService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.oa.duban.entity.DubanItemTask;
import com.oa.duban.entity.DubanItemTaskCoopDept;
import com.oa.duban.entity.DubanItemTaskCoopUser;
import com.oa.duban.entity.DubanItemTaskVo;
import com.oa.duban.mapper.DubanItemTaskMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@Service
public class DubanItemTaskService extends BaseService<DubanItemTaskMapper, DubanItemTask> {
    static Logger logger = LoggerFactory.getLogger(DubanItemTaskService.class);

    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }


    @Autowired
    DubanItemTaskCoopDeptService dubanItemTaskCoopDeptService;

    @Autowired
    DubanItemTaskCoopUserService dubanItemTaskCoopUserService;

    /**
     * 请在此类添加自定义函数
     * 保存任务
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Integer saveTask(DubanItemTaskVo dubanItemTaskVo) {
        dubanItemTaskVo.setCreateTime(new Date());
        if (StringUtils.isEmpty(dubanItemTaskVo.getProgress())) {
            dubanItemTaskVo.setProgress("0");
        }
        if (StringUtils.isEmpty(dubanItemTaskVo.getStatus())) {
            dubanItemTaskVo.setStatus("0");

        }

        if (org.springframework.util.StringUtils.isEmpty(dubanItemTaskVo.getCreateUserid())) {
            User currentUserInfo = LoginUtils.getCurrentUserInfo();
            dubanItemTaskVo.setCreateUserid(currentUserInfo.getUserid());
            dubanItemTaskVo.setCreateUsername(currentUserInfo.getUsername());
        }

        DubanItemTask dubanItemTask = new DubanItemTask();
        BeanUtils.copyProperties(dubanItemTaskVo, dubanItemTask);

        if (StringUtils.isEmpty(dubanItemTask.getId())) {
            dubanItemTask.setId(this.createKey("id"));
        } else {
            DubanItemTask dubanItemTaskQuery = new DubanItemTask(dubanItemTask.getId());
            if (this.countByWhere(dubanItemTaskQuery) > 0) {
                throw new BizException("督办任务主键重复，请修改后重试！");
            }
        }
        int insert = this.insert(dubanItemTask);

        //保存任务协办部门
        List<DubanItemTaskCoopDept> coopDepts = dubanItemTaskVo.getCoopDept();
        if (coopDepts != null && coopDepts.size() > 0) {
            coopDepts.forEach((dubanItemTaskCoopDept) -> {
                if (StringUtils.isEmpty(dubanItemTaskCoopDept.getDubanItemTaskId())) {
                    dubanItemTaskCoopDept.setDubanItemTaskId(dubanItemTask.getId());
                }
                ;

                if (StringUtils.isEmpty(dubanItemTaskCoopDept.getId())) {
                    dubanItemTaskCoopDept.setId(dubanItemTaskCoopDeptService.createKey("id"));
                } else {
                    DubanItemTaskCoopDept dubanItemTaskCoopDeptQuery = new DubanItemTaskCoopDept(dubanItemTaskCoopDept.getId());
                    if (dubanItemTaskCoopDeptService.countByWhere(dubanItemTaskCoopDeptQuery) > 0) {
                        throw new BizException("任务协办部门主键重复，请修改后重试！");
                    }
                }
                dubanItemTaskCoopDeptService.insert(dubanItemTaskCoopDept);
            });
        }

        //保存任务协办用户
        List<DubanItemTaskCoopUser> coopUsers = dubanItemTaskVo.getCoopUser();
        if (coopUsers != null && coopUsers.size() > 0) {

            coopUsers.forEach((dubanItemTaskCoopUser) -> {

                if (StringUtils.isEmpty(dubanItemTaskCoopUser.getDubanItemTaskId())) {
                    dubanItemTaskCoopUser.setDubanItemTaskId(dubanItemTask.getId());
                }

                if (StringUtils.isEmpty(dubanItemTaskCoopUser.getId())) {
                    dubanItemTaskCoopUser.setId(dubanItemTaskCoopUserService.createKey("id"));
                } else {
                    DubanItemTaskCoopUser dubanItemTaskCoopUserQuery = new DubanItemTaskCoopUser(dubanItemTaskCoopUser.getId());
                    if (dubanItemTaskCoopUserService.countByWhere(dubanItemTaskCoopUserQuery) > 0) {
                        throw new BizException("任务协办主键重复，请修改后重试！");
                    }
                }
                dubanItemTaskCoopUserService.insert(dubanItemTaskCoopUser);
            });
        }

        return insert;
    }

    /**
     * 移除任务
     *
     * @param dubanItemTask
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Integer removeDubanItemTask(DubanItemTask dubanItemTask) {

        int deleteByPk = this.deleteByPk(dubanItemTask);

        DubanItemTaskCoopDept dubanItemTaskCoopDept = new DubanItemTaskCoopDept();
        dubanItemTaskCoopDept.setDubanItemTaskId(dubanItemTask.getId());
        dubanItemTaskCoopDeptService.deleteByWhere(dubanItemTaskCoopDept);

        DubanItemTaskCoopUser dubanItemTaskCoopUser = new DubanItemTaskCoopUser();
        dubanItemTaskCoopUser.setDubanItemTaskId(dubanItemTask.getId());
        dubanItemTaskCoopUserService.deleteByWhere(dubanItemTaskCoopUser);

        return deleteByPk;
    }

    /**
     * 获取任务信息
     *
     * @param dubanItemTask
     * @param dubanItemTaskVo
     * @return
     */
    public DubanItemTaskVo getMessage(DubanItemTask dubanItemTask, DubanItemTaskVo dubanItemTaskVo) {

        //查询任务信息
        //DubanItemTask oneObject = this.selectOneObject(dubanItemTask);
        //BeanUtils.copyProperties(oneObject,dubanItemTaskVo);

        //查询任务协办部门
        DubanItemTaskCoopDept dubanItemTaskCoopDept = new DubanItemTaskCoopDept();
        dubanItemTaskCoopDept.setDubanItemTaskId(dubanItemTask.getId());
        List<DubanItemTaskCoopDept> dubanItemTaskCoopDepts = dubanItemTaskCoopDeptService.selectListByWhere(dubanItemTaskCoopDept);
        dubanItemTaskVo.setCoopDept(dubanItemTaskCoopDepts);

        //查询任务协办
        DubanItemTaskCoopUser dubanItemTaskCoopUser = new DubanItemTaskCoopUser();
        dubanItemTaskCoopUser.setDubanItemTaskId(dubanItemTask.getId());
        List<DubanItemTaskCoopUser> dubanItemTaskCoopUsers = dubanItemTaskCoopUserService.selectListByWhere(dubanItemTaskCoopUser);
        dubanItemTaskVo.setCoopUser(dubanItemTaskCoopUsers);

        return dubanItemTaskVo;
    }

    /**
     * 编辑任务
     *
     * @param taskVo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Integer editTask(DubanItemTaskVo taskVo) {
        DubanItemTask dubanItemTask = new DubanItemTask();
        Integer update = null;

        if (taskVo != null) {
            BeanUtils.copyProperties(taskVo, dubanItemTask);
            update = this.updateByPk(dubanItemTask);
        }

        List<DubanItemTaskCoopDept> coopDepts = taskVo.getCoopDept();
        if (coopDepts != null && coopDepts.size() > 0) {
            coopDepts.forEach((coopDept) -> {
                dubanItemTaskCoopDeptService.updateByPk(coopDept);
            });
        }

        List<DubanItemTaskCoopUser> coopUsers = taskVo.getCoopUser();
        if (coopUsers != null && coopUsers.size() > 0) {
            coopUsers.forEach((coopUser) -> {
                dubanItemTaskCoopUserService.updateByPk(coopUser);
            });
        }
        return update;
    }

    public List<Map<String, Object>> selectListMapByWhereAndTopQuery(IPage page, QueryWrapper qw, Map<String, Object> map) {

        //获取督办查询列表
//        List<Map<String, Object>> dubanTaskList = baseMapper.selectListMapByWhereAndTopQuery(map);
        List<Map<String, Object>> dubanTaskList = baseMapper.selectListMapByWhere(page, qw, map);

        if (!StringUtils.isEmpty(map.get("coopUsers"))) {
            if (dubanTaskList != null && dubanTaskList.size() > 0) {
                List<Map<String, Object>> dubanTaskListRemove = new ArrayList<>();

                dubanTaskList.forEach((dubanTask) -> {
                    String id = (String) dubanTask.get("id");

                    DubanItemTaskCoopUser dubanItemTaskCoopUser = new DubanItemTaskCoopUser();
                    dubanItemTaskCoopUser.setDubanItemTaskId(id);
                    List<DubanItemTaskCoopUser> dubanItemTaskCoopUsers = dubanItemTaskCoopUserService.selectListByWhere(dubanItemTaskCoopUser);

                    if (dubanItemTaskCoopUsers != null && dubanItemTaskCoopUsers.size() > 0) {
                        List<DubanItemTaskCoopUser> coopUsers = new ArrayList<>();
                        dubanItemTaskCoopUsers.forEach((coopUser) -> {
                            if (DubanItemService.useList((String[]) map.get("coopUsers"), coopUser.getUserId())) {
                                coopUsers.add(coopUser);
                            }
                        });
                        if (coopUsers.size() > 0) {
                            dubanTask.put("coopUsers", dubanItemTaskCoopUsers);
                        } else {
                            dubanTaskListRemove.add(dubanTask);
                        }
                    } else {
                        dubanTaskListRemove.add(dubanTask);
                    }
                });
                dubanTaskList.removeAll(dubanTaskListRemove);
            }
        } else {
            if (dubanTaskList != null && dubanTaskList.size() > 0) {

                dubanTaskList.forEach((dubanTask) -> {
                    String id = (String) dubanTask.get("id");
                    DubanItemTaskCoopUser dubanItemTaskCoopUser = new DubanItemTaskCoopUser();
                    dubanItemTaskCoopUser.setDubanItemTaskId(id);
                    List<DubanItemTaskCoopUser> dubanItemTaskCoopUsers = dubanItemTaskCoopUserService.selectListByWhere(dubanItemTaskCoopUser);

                    dubanTask.put("coopUsers", dubanItemTaskCoopUsers);
                });

            }
        }
        return dubanTaskList;
    }
}

